package cn.wolfcode.cloud.shop.service.impl;

import cn.wolfcode.cloud.shop.domain.User;
import cn.wolfcode.cloud.shop.exception.BusinessException;
import cn.wolfcode.cloud.shop.mapper.UserMapper;
import cn.wolfcode.cloud.shop.redis.MemberRedisKey;
import cn.wolfcode.cloud.shop.resp.MemberServerCodeMsg;
import cn.wolfcode.cloud.shop.service.IUserService;
import cn.wolfcode.cloud.shop.util.JSONUtil;
import cn.wolfcode.cloud.shop.util.MD5Util;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service
public class UserServiceImpl implements IUserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Override
    public User selectById(Long id) {
       return userMapper.selectByPrimatyKey(id);
    }

    @Override
    public String login(String mobile, String password) {

        User user = userMapper.selectByPrimatyKey(Long.parseLong(mobile));
        if(user==null){
            throw new BusinessException(MemberServerCodeMsg.USERNAME_OR_PASSWORD_ERROR);
        }

        if(!user.getPassword().equals(MD5Util.formPass2DbPass(password,user.getSalt()))){
            throw new BusinessException(MemberServerCodeMsg.USERNAME_OR_PASSWORD_ERROR);
        }

        return createToken(user);
    }


    private String createToken(User user) {
        String token = UUID.randomUUID().toString().replaceAll("-", "").substring(0, 8);
        redisTemplate.opsForValue().set(
            MemberRedisKey.USER_TOKEN.getRealKey(token),
            JSONUtil.toJsonString(user),
            30L,
            TimeUnit.MINUTES);

        return token;
    }

    @Override
    public Boolean refreshToken(String token) {

        Boolean flag = redisTemplate.hasKey(MemberRedisKey.USER_TOKEN.getRealKey(token));
        if(flag == null || !flag){
            return false;
        }

        Boolean expire = redisTemplate.expire(
            MemberRedisKey.USER_TOKEN.getRealKey(token),
            MemberRedisKey.USER_TOKEN.getExpireTime(),
            MemberRedisKey.USER_TOKEN.getTimeUnit());

        return expire != null && expire;
    }

    @Override
    public User findByToken(String token) {
        String json = redisTemplate.opsForValue().get(MemberRedisKey.USER_TOKEN.getRealKey(token));
        if(StringUtils.isNotEmpty(json)){
            return JSONUtil.parseObject(json,User.class);
        }
        return null;
    }


}
